package com.jumi.microservice.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jm.member.common.core.utils.DelFlag;
import com.jm.member.common.core.utils.ServletUtils;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.config.RedisInit;
import com.jumi.microservice.dto.request.JmUserLevelConfigUpdateRequest;
import com.jumi.microservice.entity.JmUserLevelConfig;
import com.jumi.microservice.entity.JmUserLevelConfigLog;
import com.jumi.microservice.enums.Level;
import com.jumi.microservice.service.IJmUserLevelConfigLogService;
import com.jumi.microservice.service.IJmUserLevelConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 等级配置表 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-07-30
 */
@RestController
@RequestMapping("/jm-user-level-config")
@Transactional
@Api(value = "等级配置",tags = {"等级配置接口"})
public class JmUserLevelConfigController {

    @Autowired
    IJmUserLevelConfigService configService;

    @Autowired
    IJmUserLevelConfigLogService logService;

    @GetMapping("/getLevelConfig")
    @ApiOperation("等级配置列表")
    public ResponseResult getLevelConfig(){

        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("is_del", DelFlag.normal);
        List<JmUserLevelConfig> list = configService.list(wrapper);
        list.stream().filter(l -> l.getChildrenNum()>0).forEach(l->{
            String levelValue = l.getChildrenLevel().split(",")[0];
            Level level = Level.getLevelByValue(Integer.valueOf(levelValue));
            l.setDescribe(StrUtil.format("≥ {}个{}",l.getChildrenNum(),level.getDesc()));
        });
        return ResponseResult.success(list);
    }


    @Autowired
    RedisInit redisInit;

    @PostMapping("/updateLevelConfig")
    @ApiOperation("更新等级配置")
    public ResponseResult updateLevelConfig(@Validated JmUserLevelConfigUpdateRequest request){
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();

        JmUserLevelConfig byId = configService.getById(request.getId());
        if(ObjectUtil.isNull(byId)){ return ResponseResult.error("未查询到相关记录！");}

        Integer[] childrenLevel = request.getChildrenLevel();
        Integer[] addLevel = request.getAddLevel();
        JmUserLevelConfig config=new JmUserLevelConfig();
        StringBuffer buffer=new StringBuffer();

        for (Integer value : childrenLevel) {
            Level level = Level.getLevelByValue(value);
            if(level!=null){
                buffer.append(level.getValue());
                buffer.append(",");
            }
        }
        if(request.getChildrenNum()>0 && buffer.length()==0){
            return ResponseResult.error("团队规模要求不能为空！");
        }
        config.setChildrenLevel(buffer.toString());
        //----
        buffer=new StringBuffer();
        for (Integer value : addLevel) {
            Level level = Level.getLevelByValue(value);
            if(level!=null){
                buffer.append(level.getValue());
                buffer.append(",");
            }
        }
        if(request.getAddNum()>0&&buffer.length()==0){
            return ResponseResult.error("新增团队要求不能为空！");
        }
        config.setAddLevel(buffer.toString());

        BeanUtils.copyProperties(request,config);

        config.setAdminId(adminId);
        config.setAdminName(adminName);
        config.setUpdateTime(LocalDateTime.now());

        JmUserLevelConfigLog confLog = getConfLog(byId, config);
        confLog.setData(JSONObject.toJSONString(confLog));
        confLog.setAdminId(adminId);
        confLog.setAdminName(adminName);
        logService.save(confLog);
        redisInit.initLevelConfig();
        return ResponseResult.success(configService.updateById(config));
    }

    public JmUserLevelConfigLog getConfLog(JmUserLevelConfig before,JmUserLevelConfig after){
        JmUserLevelConfigLog l=new JmUserLevelConfigLog();
        l.setLevelId(before.getId());
        l.setUpdateTime(LocalDateTime.now());
//        l.setbDownLevel(before.getLeveldownChildrenLevel());
//        l.setbDownNum(before.getLeveldownChildrenNum().toString());
//        l.setbDownSales(before.getLeveldownSales().toString());
        l.setbUpLevel(before.getChildrenLevel());
        l.setbUpNum(before.getChildrenNum().toString());
        l.setbAddLevel(before.getAddLevel());
        l.setbAddNum(before.getAddNum());
        l.setbUpSales(before.getSales().toString());
        l.setbIdentity(before.getIsIdentity().name());
        //------------------------------更改之后
//        l.setfDownLevel(after.getLeveldownChildrenLevel());
//        l.setfDownNum(after.getLeveldownChildrenNum().toString());
//        l.setfDownSales(after.getLeveldownSales().toString());
        l.setfUpLevel(after.getChildrenLevel());
        l.setfUpNum(after.getChildrenNum().toString());
        l.setfUpSales(after.getSales().toString());
        l.setfIdentity(after.getIsIdentity().name());
        l.setfAddLevel(after.getAddLevel());
        l.setfAddNum(after.getAddNum());
        return l;
    }
}
